package apibasej.basic.misc.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;

import apibasej.basic.config.ConfigManager;

public class UtilIO extends ConfigManager{

	/*
	public static byte[] readInputStream(InputStream instream) throws IOException{
		return readInputStream(instream, null);
	}

	public static byte[] readInputStream(InputStream instream, byte[] bytesReadBefore) throws IOException{
        ByteArrayOutputStream outstream = new ByteArrayOutputStream(4096);
        if(bytesReadBefore!=null && bytesReadBefore.length>0){
        	outstream.write(bytesReadBefore);
        }
        byte[] buffer = new byte[4096];
        int len; // quantidades de bytes lidos
        while ((len = instream.read(buffer)) > 0) {
            outstream.write(buffer, 0, len);
        }
        // não fechar aqui, pois pode querer continuar lendo ...
        //outstream.close();
        //instream.close();
        return outstream.toByteArray();
	}*/
	
	public static byte[] readInputStream(InputStream instream) throws IOException{
		return readInputStream(instream,false);
	}
	public static byte[] readInputStream(InputStream instream, boolean ignClose) throws IOException{
		return readInputStream(instream, ignClose, null, false);
	}
	
	public static byte[] readInputStream(InputStream instream, boolean ignClose, Integer maxLengthRead, boolean errIfMaxLen) throws IOException{
        try(@SuppressWarnings("resource")
			ByteArrayOutputStream outstream = new ByteArrayOutputStream(4096);)
			{
            byte[] buffer = new byte[4096];
            int totLenRead = 0;
            int len; // quantidades de bytes lidos
            while ((len = instream.read(buffer)) > 0) {
                outstream.write(buffer, 0, len);
                if(maxLengthRead!=null){
                	totLenRead += len;
                	if(totLenRead>=maxLengthRead){
                		if(errIfMaxLen){
                			throw new IOException("MAX LENGTH TO READ REACHED: "+maxLengthRead);
                		}else{
                			break;
                		}
                	}
                }
            }
            try {
            	outstream.flush();
				//outstream.close();//??? fechar antes do toByteArray() pode dar erro?
			} catch (Throwable ioe) {
				ConfigManager.logDefAll(Level.SEVERE,ioe.getMessage(), ioe);
			}
            return outstream.toByteArray();
        }finally{
        	if(!ignClose){
    			try {
    				instream.close();
    			} catch (Throwable ioe) {
    				ConfigManager.logDefAll(Level.SEVERE,ioe.getMessage(), ioe);
    			}
        	}
        }
	}
	
	
	public String readInputStreamText(InputStream instream) throws IOException{
		return new String( readInputStream(instream), getProp(CHARSET) );
	}	
	
	
}
